package br.unipar.flex;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

public class FlexForm extends Form implements CommandListener {
    
    public FlexMidlet flexMidlet;
    
    public TextField gasolinaTextField;
    public TextField etanolTextField;
    public TextField porcentagemTextField;
    public TextField resultadoTextField;
    
    public Command sairCommand;
    public Command calcularCommand;

    public FlexForm(FlexMidlet flexMidlet) {
        super("Compara");
        
        this.flexMidlet = flexMidlet;
        
        // COmponentes de Tela
        
        gasolinaTextField = new TextField("Gasolina", "", 10, TextField.DECIMAL);
        etanolTextField = new TextField("Etanol", "", 10, TextField.DECIMAL);
        porcentagemTextField = new TextField("Porcentagem", 
                "", 20, TextField.DECIMAL | TextField.UNEDITABLE);
        resultadoTextField = new TextField("Resultado", "", 20, TextField.UNEDITABLE);
        
        append(gasolinaTextField);
        append(etanolTextField);
        append(porcentagemTextField);
        append(resultadoTextField);
        
        // Comandos
        
        sairCommand = new Command("Sair", Command.EXIT, 0);
        calcularCommand = new Command("Calcular", Command.SCREEN, 0);
        
        addCommand(sairCommand);
        addCommand(calcularCommand);
        
        setCommandListener(this);
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == sairCommand) {
            flexMidlet.destroyApp(true);
        } else if (command == calcularCommand) {
            String gasStr = gasolinaTextField.getString();
            double gasolina = Double.parseDouble(gasStr);
            double etanol = Double.parseDouble(etanolTextField.getString());
            
            double porcentagem  = 0.0;
            if (gasolina > 0.0) {
                porcentagem = (etanol * 100) / gasolina;
            }
            
            String resultado = "";
            if (porcentagem > 70.0) {
                resultado = "Gasolina";
            } else {
                resultado = "Etanol";
            }
            resultadoTextField.setString(resultado);
            porcentagemTextField.setString(String.valueOf(porcentagem));
        }
    }
    
}
